<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="农舍名称" prop="name">
        <el-tree-select
          v-model="queryParams.farmHouseId"
          :data="deptList"
          :render-after-expand="false"
          placeholder="请选择农舍"
          @change="hangdleChange"
           style="width:240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>

    <div class="expend-box">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="box-radio">
            <span style="margin-right: 10px;">数据类型:</span>
            <el-radio-group v-model="selectedDataType" @change="handleDataTypeChange">
              <el-radio value="温度">温度</el-radio>
              <el-radio value="其他数据">其他数据</el-radio>
            </el-radio-group>
          </div>
        </el-col>
        <el-col :span="24">
          <div>
            <span style="margin-right: 10px;">展示类型:</span>
            <el-checkbox-group v-model="selectedOptions">
              <el-checkbox v-for="item in currentOptions" :key="item" :value="item">{{ item }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="expend-echarts">
      <!-- 分隔线 -->
      <el-divider />
      <div style="margin:20px" v-loading="loading" element-loading-text="努力加载中...">
        <div id="chart" ref="chartRef" style="width: 100%; height: 600px;"></div>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { debounce } from 'lodash';
import { FarmTourApi, FarmTourVO } from '@/api/farmTour/index';
import {farmHouseExpend} from '@/api/houseTour/houseOverview/index';
import { houseTourApi } from '@/api/houseTour/history/index';
import { FarmWarnApi } from '@/api/farmTour/warn/index';
import { ECAApi } from '@/api/houseTour/ECA/index';
import { EChartsType,EChartsOption  } from 'echarts';
import { onMounted, ref, reactive } from 'vue';
import * as echarts from "echarts";
import { type } from 'os';

defineOptions({ name: 'ECA' });

const deptList = ref([]); // 用于存储农舍列表
const loading = ref(true);
const farmTourValue = ref<any>(null);
const farmTourList = ref<FarmTourVO[]>([]);
const houseList = ref<any[]>([]);
const checked1 = ref(true);
const checked2 = ref(true);

const queryParams = reactive({
  name: undefined,
  createTime: [],
  farmHouseId: undefined,
  timeRange: []
});

interface weatherDataVo {
  boardTemps: number[];
}
interface SeriesItemVo {
  name: string;
  type: 'line' | 'bar';
  data: number[];
}
const queryFormRef = ref();

const chartRef = ref(null);
const myChart =ref<EChartsType | null>(null);
const weatherData = ref<weatherDataVo[]>([]); // 用于存储获取的天气数据
const labels = ref([]); // 用于存储时间标签

const dataTypes = {
  温度: [
    '温度1', '温度2', '温度3', '温度4', '温度5', '温度6', '温度7', '温度8',
    '负板温度1', '负板温度2', '负板温度3', '负板温度4', '负板温度5', '负板温度6', '负板温度7', '负板温度8',
    '室外温度', '室内温度', '目标温度'
  ],
  其他数据: ['湿度', '负压', '二氧化碳', '氨气']
};

// 当前选择的数据类型和选项
const selectedDataType = ref('温度'); // 默认选择温度
// const selectedOptions = ref([...dataTypes.温度]); // 默认选中所有温度选项
const selectedOptions = ref(['温度1']); // 默认选中 '温度1'
const currentOptions = ref(dataTypes.温度); // 初始显示温度选项

const getHouseList = async () => {
  try {
    const res = await farmHouseExpend.getHouseListApi();
    console.log(res, 'res农舍列表');
    if (res) {
      loading.value = true;
      deptList.value = res.map(item => ({
        value: item.id,
        label: item.name,
        children: item.children ? item.children.map(child => ({
          value: child.id,
          label: child.name,
        })) : []
      }));
      // 设置默认选择，选择第一个农舍的第一个子项
      if (deptList.value.length > 0 && deptList.value[0].children.length > 0) {
        queryParams.farmHouseId = deptList.value[0].children[0].value;
        // 获取默认类型，并加载数据
        const typeMapping = {
          温度: 1,
          其他数据: 2
        };
        const type = typeMapping[selectedDataType.value]; // 根据当前选择的数据类型获取 type 值
        
        // 在这里调用获取数据的方法
        await fetchDataForSelectedHouse(queryParams.farmHouseId, type);
      }
    }else{
      deptList.value = []
    }
  } catch (error) {
    console.error('请求失败:', error);
  }finally{
    loading.value = false;
  }
};
// 处理数据类型切换
const handleDataTypeChange = () => {
  currentOptions.value = dataTypes[selectedDataType.value];
  // selectedOptions.value = [...currentOptions.value];
  selectedOptions.value = [currentOptions.value[0]]; // 默认只选择第一个选项

  // 清空之前的数据
  weatherData.value = []; 
  labels.value = []; 
  // 根据选中的数据类型设置 type
  const typeMapping = {
    温度: 1,
    其他数据: 2
  };
  const type = typeMapping[selectedDataType.value]; // 获取对应的 type 值
  // 重新获取数据并更新图表
  if (queryParams.farmHouseId) {
    getECAData(queryParams.farmHouseId, type); // 传递动态的 type 值
  }
  
  initChart();
};

// 处理农舍选择变化
const hangdleChange = async (selectedHouseId) => {
  loading.value = true;
  console.log("选择的农舍ID:", selectedHouseId);
  const typeMapping = {
    温度: 1,
    其他数据: 2
  };
  const type = typeMapping[selectedDataType.value]; // 获取当前选择的数据类型对应的 type 值
  await fetchDataForSelectedHouse(selectedHouseId, type);
  loading.value = false;
};

// 根据农舍ID获取数据
const fetchDataForSelectedHouse = async (farmHouseId, type) => {
  await getECAData(farmHouseId, type); // 传递type值
};

// 获取ECA数据
const getECAData = async (farmHouseId, type) => {
  loading.value = true;
  try {
    const params = {
      farmHouseId: queryParams.farmHouseId,
      type: type,
      createTime: queryParams.timeRange.length === 2 ? queryParams.timeRange : undefined // 仅当选择了时间范围时传递
    };
    const res = await ECAApi.getECAApi(params);
    console.log(res, 'resECA');

    if (res) {
      const data = res; // 获取数据

      if (type === 1) {
        // 处理温度数据
        weatherData.value = data.map((item) => ({
          boardTemps: [
            item.boardTemp1 || 0,
            item.boardTemp2 || 0,
            item.boardTemp3 || 0,
            item.boardTemp4 || 0,
            item.boardTemp5 || 0,
            item.boardTemp6 || 0,
            item.boardTemp7 || 0,
            item.boardTemp8 || 0
          ],
          assistanTemps: [
            item.assistanTemp1 || 0,
            item.assistanTemp2 || 0,
            item.assistanTemp3 || 0,
            item.assistanTemp4 || 0,
            item.assistanTemp5 || 0,
            item.assistanTemp6 || 0,
            item.assistanTemp7 || 0,
            item.assistanTemp8 || 0
          ],
          outdoorTemperature: item.outdoorTemperature || 0,
          interTemperature: item.interTemperature || 0,
          stemperature: item.stemperature || 0
        }));
      } else if (type === 2) {
        // 处理其他数据
        weatherData.value = data.map(item => ({
          createTime: item.createTime,
          interPressure: item.interPressure || 0,
          airHumidity: item.airHumidity || 0,
          co2Concentration: item.co2Concentration || 0,
          nh3Concentration: item.nh3Concentration || 0,
        }));
      }

      // 生成时间标签
      labels.value = data.map(item => {
        const date = new Date(item.createTime); // 将时间戳转换为日期对象
        return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`; // 格式化为 YYYY-MM-DD HH:mm
      });

      // 更新图表
      initChart();
    } else {
      console.error('数据格式错误或无数据', res);
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};


const initChart = () => {
  const series: SeriesItemVo[] = []; // 用于存储系列数组

  // 根据选中的选项添加数据系列
  selectedOptions.value.forEach(option => {
    if (selectedDataType.value === '温度') {
      // 处理温度数据系列
      let index = -1; // 初始化索引为-1
      if (option.startsWith('温度')) {
        index = parseInt(option.replace('温度', '')) - 1; // 获取温度索引
        const data = weatherData.value.map(item => item.boardTemps[index]);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option.startsWith('负板温度')) {
        index = parseInt(option.replace('负板温度', '')) - 1; // 获取负板温度索引
        const data = weatherData.value.map(item => item.assistanTemps[index]);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '室外温度') {
        const data = weatherData.value.map(item => item.outdoorTemperature);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '室内温度') {
        const data = weatherData.value.map(item => item.interTemperature);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '目标温度') {
        const data = weatherData.value.map(item => item.stemperature);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      }
    } else if (selectedDataType.value === '其他数据') {
      // 处理其他数据系列
      if (option === '湿度') {
        const data = weatherData.value.map(item => item.airHumidity);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '负压') {
        const data = weatherData.value.map(item => item.interPressure);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '二氧化碳') {
        const data = weatherData.value.map(item => item.co2Concentration);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      } else if (option === '氨气') {
        const data = weatherData.value.map(item => item.nh3Concentration);
        series.push({
          name: option,
          type: 'line',
          data: data
        });
      }
    }
  });

  const option = {
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: (params) => {
        return `${params.seriesName}: ${params.value}`;
      }
    },
    legend: {
      data: series.map(s => s.name)
    },
    xAxis: {
      type: 'category',
      data: labels.value,
      axisLabel: {
        rotate: 45,
        formatter: (value) => value
      }
    },
    yAxis: {
      type: 'value'
    },
    series: series
  };

  if (myChart.value) {
    myChart.value.clear();
    myChart.value.setOption(option);
    window.addEventListener('resize', () => {
      myChart.value.resize();
    });
  } else {
    // 如果图表未初始化，则进行初始化
    myChart.value = echarts.init(chartRef.value);
    myChart.value.setOption(option);
    window.addEventListener('resize', () => {
      myChart.value.resize();
    });
  }
};

// 查询数据
const handleQuery = async () => {
  if (queryParams.farmHouseId) {
    const typeMapping = {
      温度: 1,
      其他数据: 2
    };
    const type = typeMapping[selectedDataType.value]; // 根据当前选择的数据类型获取 type 值
    // 调用获取数据的方法，传入农舍 ID、type 和时间范围
    await getECAData(queryParams.farmHouseId, type);
  }
};

const resetQuery = () => {
  queryParams.timeRange = []; // 重置时间范围
  queryFormRef.value.resetFields();
  handleQuery(); 
};


const debouncedGetHouseList = debounce(async (newValue) => {
}, 300);


// 监听选中项目的变化
watch(selectedOptions, () => {
  initChart(); // 选中项目变化时重新初始化图表
});


/** 初始化 **/
onMounted(() => {
  getHouseList()
});
</script>

<style scoped lang="scss">
.el-button-group {
  .el-button--primary:last-child {
    border-left-color: #ccc;
  }
  .is-active {
    background-color: #409EFF;
  }
}

.expend-box {
  margin: 10px 10px;
  padding: 10px;
  background-color: rgba(239, 246, 255, 0.996078431372549);
}
</style>
